package com.example.himalaya.presenters;

import com.example.himalaya.base.BaseApplication;
import com.example.himalaya.view.callback.ISubscriptionViewCallback;
import com.example.himalaya.model.dao.SubscriptionDao;
import com.example.himalaya.presenters.interfaces.ISubscriptionPresenter;
import com.example.himalaya.view.callback.ISubDaoCallback;
import com.example.himalaya.constants.Constants;
import com.example.himalaya.utils.LogUtil;
import com.ximalaya.ting.android.opensdk.model.album.Album;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.schedulers.Schedulers;

public class SubscriptionPresenter implements ISubscriptionPresenter, ISubDaoCallback {

    // Constance
    private String TAG = "SubscriptionPresenter";

    // Map
    private Map<Long, Album> mData = new HashMap<>();


    // Logic object
    private static SubscriptionPresenter sInstance;
    private final SubscriptionDao mSubscriptionDao;


    // Calllback
    private List<ISubscriptionViewCallback> mCallbacks = new ArrayList<>();

    public static SubscriptionPresenter getInstance() {
        if (sInstance == null) {
            synchronized (SubscriptionPresenter.class) {
                if (sInstance == null) {
                    sInstance = new SubscriptionPresenter();
                }
            }
        }

        return sInstance;
    }


    private SubscriptionPresenter() {
        mSubscriptionDao = SubscriptionDao.getInstance();

        mSubscriptionDao.setCallback(this);

    }

    private void listSubscriptions() {
        Observable.create(new ObservableOnSubscribe<Object>() {

            @Override
            public void subscribe(ObservableEmitter<Object> emitter) throws Exception {
                // 只调用，不处理结果
                if (mSubscriptionDao != null) {
                    mSubscriptionDao.listAlbums();
                }
            }
        }).subscribeOn(Schedulers.io()).subscribe();
    }

    @Override
    public void addSubscription(final Album album) {


        // 判断当前的订阅数量， 不能超过100
        if (mData.size() >= Constants.MAX_SUB_COUNT) {
            // 给出提示\

            for (ISubscriptionViewCallback callback : mCallbacks) {
                callback.onSubFull();
            }
            return;
        }

        Observable.create(new ObservableOnSubscribe<Object>() {

            @Override
            public void subscribe(ObservableEmitter<Object> emitter) throws Exception {
                // 只调用，不处理结果
                if (mSubscriptionDao != null) {
                    mSubscriptionDao.addAlbum(album);
                }
            }
        }).subscribeOn(Schedulers.io()).subscribe();
    }

    @Override
    public void deleteSubscription(final Album album) {

        Observable.create(new ObservableOnSubscribe<Object>() {

            @Override
            public void subscribe(ObservableEmitter<Object> emitter) throws Exception {
                // 只调用，不处理结果
                if (mSubscriptionDao != null) {
                    mSubscriptionDao.delAlbum(album);
                }
            }
        }).subscribeOn(Schedulers.io()).subscribe();
    }

    /**
     * 获取订阅列表
     */
    @Override
    public void getSubscriptionList() {
        listSubscriptions();
    }

    /**
     * 判断专辑是否已经收藏
     *
     * @param album 专辑对象
     * @return 是否已经收藏
     */
    @Override
    public boolean isSub(Album album) {
        Album result = mData.get(album.getId());

        return result != null;
    }

    @Override
    public void registerViewCallback(ISubscriptionViewCallback iSubscriptionViewCallback) {
        if (!mCallbacks.contains(iSubscriptionViewCallback)) {
            mCallbacks.add(iSubscriptionViewCallback);
        }
    }

    @Override
    public void unRegisterViewCallback(ISubscriptionViewCallback iSubscriptionViewCallback) {
        mCallbacks.remove(iSubscriptionViewCallback);
    }

    /**
     * 添加订阅的回调
     *
     * @param isSuccess 添加是否成功
     */
    @Override
    public void onAddResult(final boolean isSuccess) {
//        listSubscriptions();

        BaseApplication.getsHandler().post(new Runnable() {
            @Override
            public void run() {

                LogUtil.d(TAG, "callback length  --->" + mCallbacks.size());

                for (ISubscriptionViewCallback callback : mCallbacks) {
                    callback.onAddResult(isSuccess);

                }
            }
        });
    }

    /**
     * 删除订阅的回调
     *
     * @param isSuccess 删除是否成功
     */
    @Override
    public void onDelResult(final boolean isSuccess) {
//        listSubscriptions();

        BaseApplication.getsHandler().post(new Runnable() {
            @Override
            public void run() {
                for (ISubscriptionViewCallback callback : mCallbacks) {
                    callback.onDeleteResult(isSuccess);
                }
            }
        });
    }

    /**
     * 获取的订阅列表
     *
     * @param result 获取的结果列表
     */
    @Override
    public void onSubListLoaded(final List<Album> result) {

        mData.clear();

        for (Album album : result) {
            mData.put(album.getId(), album);

//            LogUtil.d(TAG, "album" + album.getAlbumTitle());
        }

        // 通知UI

        BaseApplication.getsHandler().post(new Runnable() {
            @Override
            public void run() {
                for (ISubscriptionViewCallback callback : mCallbacks) {
                    callback.onSubscriptsLoaded(result);
                }
            }
        });
    }


}
